package com.mall.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.common.service.impl.CrudServiceImpl;
import com.mall.common.utils.ConvertUtils;
import com.mall.common.utils.DateUtils;
import com.mall.coupon.dao.SeckillSessionDao;
import com.mall.coupon.dto.SeckillSessionDTO;
import com.mall.coupon.dto.SeckillSkuRelationDTO;
import com.mall.coupon.entity.SeckillSessionEntity;
import com.mall.coupon.entity.SeckillSkuRelationEntity;
import com.mall.coupon.service.SeckillPromotionService;
import com.mall.coupon.service.SeckillSessionService;
import com.mall.coupon.service.SeckillSkuNoticeService;
import com.mall.coupon.service.SeckillSkuRelationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 秒杀活动场次
 *
 * @author xjc xjc@163.com
 * @since 1.0.0 2022-07-17
 */
@Service
public class SeckillSessionServiceImpl extends CrudServiceImpl<SeckillSessionDao, SeckillSessionEntity, SeckillSessionDTO> implements SeckillSessionService {

    @Resource
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public QueryWrapper<SeckillSessionEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<SeckillSessionEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public List<SeckillSessionDTO> getLatest3DaySession() {
        QueryWrapper<SeckillSessionEntity> queryWrapper = new QueryWrapper<>();
        LocalDate curr = LocalDate.now();
        String start = curr+" 00:00:00";
        String end =curr.plusDays(2)+" 23:59:59";
        queryWrapper.between("start_time",start,end);

        List<SeckillSessionEntity> selectList = baseDao.selectList(queryWrapper);
        List<SeckillSessionDTO> list = selectList.stream().map(session -> {
            Long sessionId = session.getId();
            QueryWrapper<SeckillSkuRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("promotion_session_id", sessionId);
            List<SeckillSkuRelationEntity> product = seckillSkuRelationService.listByWapper(wrapper);
            SeckillSessionDTO sessionDTO = ConvertUtils.sourceToTarget(session, SeckillSessionDTO.class);
            sessionDTO.setRelationDTOList(ConvertUtils.sourceToTarget(product, SeckillSkuRelationDTO.class));
            return sessionDTO;
        }).collect(Collectors.toList());

        return list;
    }
}